import type { Router } from "vue-router"
import { setRouteChange } from "@@/composables/useRouteListener"
import { useTitle } from "@@/composables/useTitle"
import { getTokenValue } from "@@/utils/cache/cookies"
import NProgress from "nprogress"
import { LayoutModeEnum } from "@/common/constants/app-key"
import { getCurrentUserRolesApi } from "@/pages/login/apis"
import { usePermissionStore } from "@/pinia/stores/permission"
import { useSettingsStore } from "@/pinia/stores/settings"
import { useUserStore } from "@/pinia/stores/user"
import { routerConfig } from "@/router/config"
import { isWhiteList } from "@/router/whitelist"

NProgress.configure({ showSpinner: false })

const { setTitle } = useTitle()

const LOGIN_PATH = "/login"

export function registerNavigationGuard(router: Router) {
  // 全局前置守卫
  router.beforeEach(async (to, _from) => {
    NProgress.start()
    const userStore = useUserStore()
    const permissionStore = usePermissionStore()
    const settingsStore = useSettingsStore()
    // 如果没有登录
    if (!getTokenValue()) {
      // 如果在免登录的白名单中，则直接进入
      if (isWhiteList(to)) return true
      // 其他没有访问权限的页面将被重定向到登录页面
      return `${LOGIN_PATH}?redirect=${encodeURIComponent(to.fullPath)}`
    }
    // 如果已经登录，并准备进入 Login 页面，则重定向到主页
    if (to.path === LOGIN_PATH) return "/"
    // 每次路由跳转都重新获取当前角色列表
    let roles: string[] = []
    try {
      const res = await getCurrentUserRolesApi()
      roles = Array.isArray(res.data) ? res.data : []
    } catch {
      roles = routerConfig.defaultRoles
    }
    userStore.roles = roles

    // 根据角色生成可访问路由，并仅在不存在时添加，避免重复注入
    permissionStore.setRoutes(roles)
    let hasNewRoutes = false
    permissionStore.addRoutes.forEach((route) => {
      if (route.name && !router.hasRoute(route.name)) {
        router.addRoute(route)
        hasNewRoutes = true
      }
    })

    // 学生布局：顶部导航 + 隐藏标签栏
    if (roles.includes("STUDENT")) {
      settingsStore.layoutMode = LayoutModeEnum.Top
      settingsStore.showTagsView = false
      settingsStore.showLogo = true
    } else {
      settingsStore.layoutMode = LayoutModeEnum.Left
      settingsStore.showTagsView = true
      settingsStore.showLogo = true
    }

    return hasNewRoutes ? { ...to, replace: true } : true
  })

  // 全局后置钩子
  router.afterEach((to) => {
    setRouteChange(to)
    setTitle(to.meta.title)
    NProgress.done()
  })
}
